<template>
  <div>
    <h2>账号设置</h2>
    <h3>个人信息</h3>
    <div class="user-info">
      <div class="items">
        <div class="item">用户名</div>
        <div class="value">{{ userInfo?.name }}</div>
        <div>
          <el-button type="success" @click="editName">编辑昵称</el-button>
        </div>
      </div>
      <div class="items">
        <div class="item">头像</div>
        <div class="value">
          <el-button type="success" @click="editPic">更改头像</el-button>
        </div>
      </div>
    </div>
  </div>
  <el-dialog width="20rem" title="编辑昵称" v-model="editVisible" :before-close="handleClose" class="edit-name">
    <el-form ref="formRef" :model="form" label-width="80px" :rules="rules">
      <el-form-item label="昵称">
        <el-input v-model="form.name" placeholder="请输入昵称" clearable></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="editVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </div>
  </el-dialog>
  <el-dialog width="40rem" title="裁剪头像" v-model="editPicVisible" :before-close="handlePicClose" class="edit-pic">
    <div class="cropper-container">

      <div class="pic-container">
        <img :src="userInfo?.pic" alt="" id="picImage" ref="picImageRef">
        <!-- <CropperCanvas class="cropper-canvas" background ref="cropperCanvasRef">
          <CropperImage :src="userInfo?.pic" alt="Picture" rotatable scalable skewable translatable></CropperImage>
          <CropperShade hidden></CropperShade>
          <CropperHandle action="select" plain></CropperHandle>
          <CropperSelection id="cropperSelection" initial-aspect-ratio="1.5" initial-coverage="0.5" movable resizable
            @change="onCropperSelectionChange">
            <CropperHandle action="move" theme-color="rgba(255, 255, 255, 0.35)"></CropperHandle>
            <CropperHandle action="n-resize"></CropperHandle>
            <CropperHandle action="e-resize"></CropperHandle>
            <CropperHandle action="s-resize"></CropperHandle>
            <CropperHandle action="w-resize"></CropperHandle>
            <CropperHandle action="ne-resize"></CropperHandle>
            <CropperHandle action="nw-resize"></CropperHandle>
            <CropperHandle action="se-resize"></CropperHandle>
            <CropperHandle action="sw-resize"></CropperHandle>
          </CropperSelection>
        </CropperCanvas> -->
        <div class="cropper-tools">
          <el-button type="primary" @click="crop">裁剪</el-button>
          <el-button type="primary" @click="handlePicSave">保存</el-button>
        </div>
      </div>
      <div class="preview-container">
        <!-- <div class="preview-box" id="previewBox" ref="cropperBoxRef"></div> -->
        <!-- <cropper-viewer class="preview-box"></cropper-viewer> -->
        <div class="preview-circle" id="previewCircle" ref="cropperCircleRef"></div>
        <!-- <cropper-viewer selection="#cropperSelection" class="preview-box"></cropper-viewer>
        <cropper-viewer selection="#cropperSelection" class="preview-circle"></cropper-viewer> -->
      </div>

    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, nextTick } from "vue";
import User from "@/utils/user";
import type { UserInfo } from "@/utils/user";
import { ElForm, ElMessage } from "element-plus";
import { updateUserInfo } from "@/api/user";
import { useUserStore } from "@/store/models/user";
import Cropper, { CropperSelection } from 'cropperjs';
import { create } from "domain";
// 导入store
const userStore = useUserStore();
/**
 * 用户信息
 */
let userInfo: UserInfo | null = userStore.getUserInfo;

const editVisible = ref(false);
/**
 * 表单引用
 */
const formRef = ref<typeof ElForm | null>(null); // 表单引用
/**
 * 表单数据
 */
const form = ref<{ name: string }>({
  name: "",
});
/**
 * 表单验证规则
 */
const rules = {
  name: [
    { required: true, message: "请输入昵称", trigger: "blur" },
    { min: 2, max: 10, message: "昵称长度在2到10个字符", trigger: "blur" },
  ],
};
const handleClose = () => {
  editVisible.value = false;
};
/**
 * 编辑昵称
 */
const editName = () => {
  editVisible.value = true;
  form.value.name = userStore.getUserInfo?.name || "";
};


const handleSubmit = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      // 表单验证通过
      let params = {
        name: form.value.name,
        id: userStore.getUserInfo?.id,
      }
      //发起请求
      updateUserInfo(params).then((res: any) => {
        if (res.code === 200) {
          User.instance.getUserInfoById()
          editVisible.value = false;
          userInfo.name = form.value.name;
          ElMessage.success('修改成功')
        }
      });
    }
  });
  editVisible.value = false;
};


// 实例化cropper
const cropper = ref<Cropper>();

// 代理元素
const cropperCanvasRef = ref<HTMLCanvasElement>();

// const cropperBoxRef = ref<HTMLDivElement>();
const cropperCircleRef = ref<HTMLDivElement>();

/**
 * 编辑头像
 */
const editPic = () => {
  editPicVisible.value = true;
  // 异步加载图片
  nextTick(() => {
    try {      
      // 实例化cropper
      cropper.value = new Cropper("#picImage");
      console.log('cropper', cropper.value);

    }catch (error) {
      console.error(error);
      ElMessage.error('图片加载失败');
      return;
    }

  });
};


const onCropperSelectionChange = (e: any) => {
  console.log('onCropperSelectionChange', e);
  if (!cropperCanvasRef.value) {
    return;
  }
}

const cropper_pic = ref<HTMLCanvasElement>();

/**
 * 裁剪
 */
const crop = () => {
  try {
    // const previewBox = document.querySelector(".preview-container")
    // console.log('pre', previewBox);
    // let croppedData = new CropperSelection()
    // console.log('croppedData', croppedData);
    
    // 裁剪
    // croppedData.value =
    // cropper.value?.getCropperCanvas()?.$toCanvas().then((res) => {
      // console.log('all-tocanvas', res);
      // previewBox?.append(res)
    // })
    cropper.value?.getCropperSelection()?.$toCanvas().then((res) => {
      res.style.width = '10rem';
      res.style.height = '10rem';
      res.addEventListener('click', () => {
        res.remove()
      })
      console.log('res', res);
      // let resClone = res.cloneNode(true)

      // cropperBoxRef.value?.children[0]?.remove()
      cropperCircleRef.value?.children[0]?.remove()
      // previewBox?.append(res)
      // cropperBoxRef.value?.append(resClone)
      cropperCircleRef.value?.append(res)

      cropper_pic.value = res;

    })//cropper-selection

  } catch (error) {
    console.error(error);
    ElMessage.error('裁剪失败');
    return;
  }
};

const handlePicSave = () => {
  if (!cropper_pic.value) {
    ElMessage.error('请先裁剪图片');
    return;
  }
  // const formData = new FormData();
  //canvas转图片

  

  //创建a标签
  const a = document.createElement('a');
  a.download = 'avatar.png';
  a.href = cropper_pic.value.toDataURL("image/png");
  a.click();
  a.remove();
  
  
  // formData.append('file', blob , 'avatar.png');
  // 上传图片

};
function convertCanvasToImage(canvas: HTMLCanvasElement) {
    var image = new Image();
    image.src = canvas.toDataURL("image/png");
    return image;
}



/**
 * 裁剪头像弹窗
 */
const editPicVisible = ref(false);
const handlePicClose = () => {
  editPicVisible.value = false;
};


</script>

<style scoped lang="scss">
.el-dialog {
  border-radius: 2rem;

  .dialog-footer {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

h2 {
  margin-top: 2rem;
}

h3 {
  margin-top: 1.5rem;
}


.user-info {
  width: 30rem;
  background-color: #333333;
  padding: 1.25rem;
  margin-top: 1rem;
  border-radius: 1rem;
  color: #fff;

  // gap: 0 1rem;
  .items {
    margin-top: 1rem;
  }

  .item {
    font-size: 0.8rem;

  }

  .value {
    margin: 0.5rem 0;
  }
}

.cropper-container {
  width: 100%;
  height: 30rem;

  display: flex;
  justify-content: center;
  align-items: center;


  // background-color: ;
  .pic-container {
    width: 70%;
    height: 70%;
    background-color: #ccc;
    // overflow: hidden;
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;

    img {
      display: block;
      height: 100%;
      min-width: 100%;
      width: 20rem;
      // background-repeat: no-repeat;
    }

    .cropper-tools {
      width: 100%;
      height: 2rem;
      padding: 1rem 0;
    }

    :deep(cropper-canvas) {
      height: 100%;
      width: 100%;
    }

    .cropper {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 1;
      background-color: rgba(0, 0, 0, 0.5);
      display: flex;
      justify-content: center;
      align-items: center;
      // cursor: crosshair;
    }
  }

  .preview-container {
    width: 30%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    padding: 1rem;

    .preview-box {
      width: 10rem;
      height: 10rem;
      border: 1px solid #ccc;
      // background-color: #f0f;
      border-radius: 1rem;
      overflow: hidden;
    }

    .preview-circle {
      width: 10rem;
      height: 10rem;
      // background-color: #ff0;
      border: 1px solid #ccc;
      border-radius: 50%;
      margin-top: 1rem;
      overflow: hidden;
      //  position: absolute;
      //  top: 50%;
      //  left: 50%;
      //  transform: translate(-50%, -50%);
    }
  }

}

.cropper-hidden {
  display: none;
}
</style>